package com.year.shiyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.year.shiyi.common.exception.BusinessException;
import com.year.shiyi.common.utils.DateUtils;
import com.year.shiyi.entity.mybatis.SysCaptchaEntity;
import com.year.shiyi.mapper.SysCaptchaMapper;
import com.year.shiyi.service.SysCaptchaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * <p>
 * 系统验证码 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2021-02-02
 */
@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptchaEntity> implements SysCaptchaService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(HttpServletResponse response, String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("uuid不能为空");
        }
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String code = producer.createText();
        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        this.save(captchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String captcha) {
        SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
        if(captchaEntity == null){
            return false;
        }
        this.remove(new QueryWrapper<SysCaptchaEntity>().eq("uuid", captchaEntity.getUuid()));
        return captchaEntity.getCode().equalsIgnoreCase(captcha) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis();
    }
}
